// pages/order/refund/index.js
import {
  find
} from '../../../api/order';
import {
  returns
} from '../../../api/askfor';
const util = require('../../../utils/util.js')
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    refundForm: [
      { title: '预约不上' },
      { title: '商家营业但不接待' },
      { title: '商家停业/装修/转让' },
      { title: '这家吃过了，不满意' },
      { title: '朋友/网上评价不好' },
      { title: '买多了/买错了' },
      { title: '计划有变，没时间消费' },
      { title: '后悔了，不想买了' }
    ],
    refundTitle: '预约不上',
    refundIndex: 0,
    refundTextarea: '',
    id: '',
    orderForm:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    this.findClick(options.id)
    this.data.id = options.id
  },
  chooseClikc(data) {
    console.log(data)
    this.data.refundIndex = data.currentTarget.dataset.index
    this.data.refundTitle = this.data.refundForm[data.currentTarget.dataset.index].title
    this.setData({
      refundIndex: this.data.refundIndex,
      refundTitle: this.data.refundTitle
    })
  },
  textareaClick(data) {
    console.log(data)
    this.data.refundTextarea = data.detail.value,
      this.setData({
        refundTextarea: this.data.refundTextarea
      })
  },
  findClick(data) {
    var _this = this
    console.log(data)
    find(data).then(
      res => {
        if (res.type == 'success') {
          res.data.order.itemList.forEach(item=>{
             item.returnQuantity = item.availableReturnQuantity
          })
          _this.data.orderForm = res.data.order
          _this.setData({
            orderForm: _this.data.orderForm
          })
        }
      }
    ).catch(error => {
      console.log(error)
    })
  },
  returnsClick() {
    var _this = this
    var itemList = []
    _this.data.orderForm.itemList.forEach(function (item) {
      if (item.returnQuantity != 0) {
        itemList.push(item)
      }
    })
    var memoData = {
      reason: _this.data.refundTitle,
      memo: _this.data.refundTextarea
    }
    wx.showLoading({
      title: '加载中',
      mask:true
    })
    returns(itemList, memoData, _this.data.id).then(
      res => {
        wx.hideLoading()
        if (res.type == 'success') {
          wx.redirectTo({
            url: '/pages/order/refund/details?id=' + res.data.id,
          })
        }
      }
    ).catch(error => {
      wx.hideLoading()
      console.log(error)
    })
  },
})
